﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Ccr.Core;
using test.XcoAppSpaces.Core;
using XcoAppSpaces.Core;

namespace testApp.XcoAppSpaces.CF
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void btTest_Click(object sender, EventArgs e)
		{
			TestWorkerLocalAndRemote();
		}


		private void TestWorkerLocalAndRemote()
		{
			using (XcoAppSpace space1 = new XcoAppSpace("tcp.port=8001"),
							   space2 = new XcoAppSpace("tcp.port=8002"))
			{
				//Assert.IsTrue(spaceAddress1.Equals(space1.Address, StringComparison.OrdinalIgnoreCase));
				//Assert.IsTrue(spaceAddress2.Equals(space2.Address, StringComparison.OrdinalIgnoreCase));

				//run worker
				space1.RunWorker<TestWorkerContract, MyTestWorker>("test");
				MyTestWorker localWorker = (MyTestWorker)space1.Resolve<TestWorkerContract>("test");

				//test for local worker access
				localWorker.Post(1);
				Thread.Sleep(100);
				//Assert.AreEqual(1, localWorker.intMsg);

				//connect to remote worker
				TestWorkerContract remoteWorker = //(workerUri != null ? 
					//space2.ConnectWorker<TestWorkerContract>(workerUri) : 
					space2.ConnectWorker<TestWorkerContract>(Dns.GetHostName() + ":8001/test"); //);
				TestWorkerContract remoteWorker2 = space2.Resolve<TestWorkerContract>();
				//Assert.AreSame(remoteWorker, remoteWorker2);

				//tests for remote worker access and remote port
				remoteWorker.Post(2);
				remoteWorker.Post("test");
				Thread.Sleep(100);
				PortSet<int, string> responsePort = new PortSet<int, string>();
				remoteWorker.Post(responsePort);
				Thread.Sleep(500);
				//Assert.AreEqual(2, localWorker.intMsg);
				//Assert.AreEqual("test", localWorker.strMsg);
				//Assert.AreEqual(1, responsePort.P0.ItemCount);
				//Assert.AreEqual(0, responsePort.P1.ItemCount);
				int postedInt = responsePort;
				//Assert.AreEqual(2, postedInt);
			}
		}

		private void btTestRemote_Click(object sender, EventArgs e)
		{
			using (XcoAppSpace space = new XcoAppSpace("tcp.port=8000"))
			{
				var worker = space.ConnectWorker<Port<string>>("sphaere:8000");
				worker.Post("test1");
				worker.Post("test2");
				worker.Post("test3");

				var worker2 = space.ConnectWorker<Port<Port<string>>>("sphaere:8000");
				var responsePort = new Port<string>();
				space.Receive(responsePort, msg => this.Invoke((Action)(() => MessageBox.Show(msg))));
				worker2.Post(responsePort);

				Thread.Sleep(10000);
			}
		}
	}
}